package com.smz.config;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    public static final String CONTENT_TYPE = "application/json;charset=UTF-8";

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private JdbcTokenRepositoryImpl jdbcTokenRepository;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/page/login.html","/js/**","/css/**").permitAll()
                .antMatchers("/page/functions/**","/page/role/**","/page/user/**").hasRole("管理员") //必须有对应角色才能访问
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/page/login.html")
                .loginProcessingUrl("/doLogin")
                .successHandler((req,resp,auth)->{
                    resp.setContentType(CONTENT_TYPE);
                    Object principal = auth.getPrincipal();
                    resp.getWriter().print(new ObjectMapper().writeValueAsString(principal));
                    resp.getWriter().close();
                })
                .failureHandler((req,resp,auth)->{
                    resp.setContentType(CONTENT_TYPE);
                    resp.getWriter().print("{\"msg\":\"账号或密码错误\"}");
                    resp.getWriter().close();
                })
//                .and()
//                .exceptionHandling() //未进行登录请求的处理
//                .authenticationEntryPoint((req,resp,auth)->{
//                    resp.setContentType(CONTENT_TYPE);
//                    resp.getWriter().print("{\"msg\":\"你没有权限访问\"}");
//                    resp.getWriter().close();
//                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((req,resp,auth) -> {
                    resp.setContentType(CONTENT_TYPE);
                    resp.getWriter().print("{\"msg\":\"注销成功\"}");
                    resp.getWriter().close();
                })
                .and()
                .rememberMe()
                .rememberMeParameter("rememberMe")
                .tokenRepository(jdbcTokenRepository)
                .tokenValiditySeconds(24 * 3600)
                .and()
                .csrf().disable();
        //配置http解决iframe不能跳转的问题
        http.headers().frameOptions().sameOrigin().httpStrictTransportSecurity().disable();
    }

/*    @Bean
    CorsConfigurationSource corsConfigurationSource(){
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:8888"));
        configuration.addAllowedMethod("POST,PUT");
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }*/
}
